﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <script type="text/javascript">
        //简单值: null ,boolean , number ,string(不能是undefined)
        var simpleJSON = 5;
        console.log(JSON.parse(simpleJSON))

        //对象:属性必须用双引号
        var objJSON = '{"name":"张三","age": 15}';
        console.log(JSON.parse(objJSON));


        //数组:
        var arrJSON = '[{"name":"张三","age": 15},{"name":"李四","age": 20}]';
        console.log(JSON.parse(arrJSON));

        //---------------------------------------------------------------------------

        //序列化简单值
        var simple = 5;
        console.log(JSON.stringify(simple));

        //序列化单个对象
        var person = {
            name: "张三",
            age : 12
        }
        console.log(JSON.stringify(person));

        //序列化数组
        var arr = [];
        var person2 = {
            name: "张三",
            age: 12,
            weight: 100,
            height: 178,
            score: {
                english: 100,
                math: 90,
                chinese : 80
            }
            
        }
        arr.push(person, person2);
        console.log(JSON.stringify(arr));

        //---------------------------------------------------------------------------

        //序列化：选项过滤
        var arrFilter = ["name", "age"];
        console.log(JSON.stringify(person2, arrFilter));

        //序列化:函数过滤
        var funcFilter = function(key , value){
            switch (key) {
                case "name": return "你好" + value;
                case "age": return 30;
                case "weight": return undefined;
                default: return value;
            }
        }
        console.log(JSON.stringify(person2, funcFilter));
        
        //序列化带缩进:自动插入换行符， 只缩进不换行是没有意义的 。
        console.log(JSON.stringify(person2, null, 4));

        //toJSON():由于自定义的序列化
        var person3 = {
            name: "张三",
            age: 12,
            weight: 100,
            height: 178,
            score: {
                english: 100,
                math: 90,
                chinese: 80
            },
            toJSON: function(){
                return this.score
            }
        }
        console.log(JSON.stringify(person3, null, 4));

        //stringify（）序列化的顺序 : toJSON , funcFilter
    </script>
</body>
</html>
